package ahpu.piconet.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ahpu.piconet.domin.Data;
import ahpu.piconet.service.DataService;

@Controller
public class DataController {

	@Autowired
	private DataService dataService;

	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static ObjectMapper mapper = new ObjectMapper();

	private static JsonFactory factory = mapper.getJsonFactory();

	@RequestMapping("getDataByPageAndLimit")
	public void getDataByPageAndLimit(String start, String end, String page,
			HttpServletResponse response) {

		if (!start.equals("") || !end.equals("")) {
			String starttime = start.replace("T", " ");
			System.out.println(start);
			String endtime = end.replace("T", " ");
			int queryResults = dataService.findCountByLimit(starttime, endtime);
			System.out.println(queryResults);
			List<Data> datas = dataService.findByDate(starttime, endtime,
					Integer.parseInt(page), 10);
			JSONArray array = new JSONArray();
			for (Data data : datas) {
				JSONObject jo = new JSONObject();
				jo.put("id", data.getId());
				jo.put("electricity", data.getElectricity());
				jo.put("voltage", data.getVoltage());
				df.format(data.getTimer());
				jo.element("timer", data.getTimer().toString());
				array.add(jo);
			}
			JSONObject result = new JSONObject();
			result.put("records", array);

			result.put("totalRecords", queryResults);
			try {
				writeJSON(response, result);
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else {
			List<Data> records = dataService.findByLimit(
					Integer.parseInt(page), 10);
			System.out.println(records.get(2).getTimer());
			int toltalResults = dataService.findAllCount();
			JsonObject object = new JsonObject();
			// Gson gson = new Gson();
			// JsonElement element = gson.toJsonTree(records);
			// object.add("records", element);
			// object.addProperty("totalRecords", toltalResults);
			JSONArray array = new JSONArray();
			for (Data data : records) {
				JSONObject jo = new JSONObject();
				jo.put("id", data.getId());
				jo.put("electricity", data.getElectricity());
				jo.put("voltage", data.getVoltage());
				df.format(data.getTimer());
				jo.element("timer", data.getTimer().toString());
				array.add(jo);
			}
			JSONObject result = new JSONObject();
			result.put("records", array);
			result.put("totalRecords", toltalResults);
			try {
				writeJSON(response, result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	@RequestMapping("listAll")
	public void listAll(HttpServletResponse response, String page) {
		List<Data> records = dataService
				.findByLimit(Integer.parseInt(page), 10);
		System.out.println(records.get(2).getTimer());
		int toltalResults = dataService.findAllCount();
		JsonObject object = new JsonObject();
		// Gson gson = new Gson();
		// JsonElement element = gson.toJsonTree(records);
		// object.add("records", element);
		// object.addProperty("totalRecords", toltalResults);
		JSONArray array = new JSONArray();
		for (Data data : records) {
			JSONObject jo = new JSONObject();
			jo.put("id", data.getId());
			jo.put("electricity", data.getElectricity());
			jo.put("voltage", data.getVoltage());
			df.format(data.getTimer());
			jo.element("timer", data.getTimer().toString());
			array.add(jo);
		}
		JSONObject result = new JSONObject();
		result.put("records", array);
		result.put("totalRecords", toltalResults);
		try {
			writeJSON(response, result);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "expordDatas", method = { RequestMethod.POST,RequestMethod.GET })
	public void expordDatas(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("ids") String[] ids)
			throws Exception {
		List<Data> dataLists = dataService.queryExportedForestry(ids);
		// 创建一个新的Excel
		HSSFWorkbook workBook = new HSSFWorkbook();
		// 创建sheet页
		HSSFSheet sheet = workBook.createSheet("电流电压信息");
		// 设置第一行为Header
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(0);
		HSSFCell cell1 = row.createCell(1);
		HSSFCell cell2 = row.createCell(2);
		HSSFCell cell3 = row.createCell(3);
		cell0.setCellValue("编号");
		cell1.setCellValue("电流");
		cell2.setCellValue("电压");
		cell3.setCellValue("日期");
		for (int i = 0; i < dataLists.size(); i++) {
			Data data = dataLists.get(i);
			row = sheet.createRow(i + 1);
			cell0 = row.createCell(0);
			cell1 = row.createCell(1);
			cell2 = row.createCell(2);
			cell3 = row.createCell(3);
			cell0.setCellValue(data.getId().toString());
			cell1.setCellValue(data.getElectricity());
			cell2.setCellValue(data.getVoltage());
			cell3.setCellValue(data.getTimer().toString());
			sheet.setColumnWidth(0, 6000);
			sheet.setColumnWidth(1, 6000);
			sheet.setColumnWidth(2, 6000);
			sheet.setColumnWidth(3, 6000);
		}
		response.reset();
		response.setContentType("application/msexcel;charset=UTF-8");
		try {
			response.addHeader("Content-Disposition",
					"attachment;filename=file.xls");
			OutputStream out = response.getOutputStream();
			workBook.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void writeJSON(HttpServletResponse response, Object obj)
			throws IOException {
		response.setContentType("text/html;charset=utf-8");
		JsonGenerator responseJsonGenerator = factory.createJsonGenerator(
				response.getOutputStream(), JsonEncoding.UTF8);
		responseJsonGenerator.writeObject(obj);
	}
}
